package com.smooware.icms.sync;

import java.util.Date;

import android.content.Context;

import com.smooware.icms.util.PreferenceHelper;

/**
 * Used to store security settings and values. To perform simple security
 * verifications.
 * 
 * @author Orest Vovchak
 */
public class ICMSSecurityManager {
	private static final String IS_TRUSTED_ACCESS_KEY = "is_trusted_access";
	private static final String IS_AUTHORIZED_KEY = "is_authorized";
	private static final String LAST_AUTHORIZATION_CHECK_TIME_KEY = "last_authorization_check_time";
	private static final String AUTHORIZATION_TIMEOUT_IN_MINUTES_KEY = "authorization_timeout_in_minutes";

	private static final int DEFAULT_AUTHORIZATION_TIMEOUT = 300000;

	private static final long MILLISECONDS_IN_MINUTE = 60000;

	private final Context context;

	public ICMSSecurityManager(final Context context) {
		this.context = context;
	}

	public boolean isTrustedAccess() {
		long lastTime = getLastAuthorizationTime();

		if (lastTime == 0) {
			return false;
		}

		long currentTime = new Date().getTime() / MILLISECONDS_IN_MINUTE;

		if (Math.abs(currentTime - lastTime) < DEFAULT_AUTHORIZATION_TIMEOUT) {
			return PreferenceHelper.getBooleanFromPreferences(context,
					IS_TRUSTED_ACCESS_KEY, false);
		} else {
			setTrustedAccessFalse();
			return false;
		}
	}

	public void setTrustedAccessTrue() {
		PreferenceHelper.setBooleanToPreferences(context,
				IS_TRUSTED_ACCESS_KEY, true);
	}

	public void setTrustedAccessFalse() {
		PreferenceHelper.setBooleanToPreferences(context,
				IS_TRUSTED_ACCESS_KEY, false);
	}

	public int getAuthorizationTimeout() {
		return PreferenceHelper.getIntegerFromPreferences(context,
				AUTHORIZATION_TIMEOUT_IN_MINUTES_KEY,
				DEFAULT_AUTHORIZATION_TIMEOUT);
	}

	public void setAuthorizationTimeout(final int timeout) {
		PreferenceHelper.setIntegerToPreferences(context,
				AUTHORIZATION_TIMEOUT_IN_MINUTES_KEY, timeout);
	}

	public boolean isAuthorized() {
		return PreferenceHelper.getBooleanFromPreferences(context,
				IS_AUTHORIZED_KEY, false);
	}

	public void setAuthorizedTrue() {
		markAuthorizationTime();

		PreferenceHelper.setBooleanToPreferences(context, IS_AUTHORIZED_KEY,
				true);
	}

	public void setAuthorizedFalse() {
		PreferenceHelper.setBooleanToPreferences(context, IS_AUTHORIZED_KEY,
				false);
	}

	public void markAuthorizationTime() {
		long currentTime = new Date().getTime() / MILLISECONDS_IN_MINUTE;

		PreferenceHelper.setLongToPreferences(context,
				LAST_AUTHORIZATION_CHECK_TIME_KEY, currentTime);
	}

	public long getLastAuthorizationTime() {
		return PreferenceHelper.getLongFromPreferences(context,
				LAST_AUTHORIZATION_CHECK_TIME_KEY, 0);
	}
}
